import json

from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.request import Request
from rest_framework.response import Response
from rest_framework import status

from drf_shop_admin.utils.jwt_util import JwtUtil
from users.serializers.oauth import LoginSerializer, ResetPasswordSerializer
from users.models import User

class LoginAPIView(APIView):
    """登录视图"""
    authentication_classes = []
    def post(self, request: Request, *args, **kwargs):
        serializer = LoginSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)

        username = serializer.validated_data.get('username')
        password = serializer.validated_data.get('password')

        ret = {'msg': 'success', 'errors': '', 'code': '', 'data': ''}

        try:
            user = User.objects.filter(Q(username=username)).first()
        except (User.DoesNotExist, User.MultipleObjectsReturned):
            ret['errors'] = '用户名错误或者不存在'
            return Response(ret, status=status.HTTP_204_NO_CONTENT)
        else:
            if not user:
                ret['errors'] = '用户名错误或者不存在'
                return Response(ret, status=status.HTTP_204_NO_CONTENT)

        if user.check_password(password):
            token = JwtUtil.gen_jwt_token({'id': user.id})
            ret['data'] = {'token': token}
            return Response(ret, status=status.HTTP_200_OK)
        else:
            ret['errors'] = '密码错误'
            return Response(ret, status=status.HTTP_204_NO_CONTENT)

class ResetPasswordAPIView(APIView):
    """修改密码视图"""
    def patch(self, request: Request, *args, **kwargs):
        ret = {'msg': 'success', 'errors': '', 'code': '', 'data': ''}
        serializer = ResetPasswordSerializer(instance=request.user, data=request.data, partial=True)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        ret['data'] = serializer.validated_data
        return Response(ret, status=status.HTTP_201_CREATED)